﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

using System.Drawing;

namespace LowLevelGraphics.Filter
{
    public class ShiftOffset : BaseImageFilter
    {
        protected bool m_bModeMin = true;

        public ShiftOffset()
        {
        }

        internal ShiftOffset(ShiftOffset _shiftOffset)        
        {
            m_bModeMin = _shiftOffset.m_bModeMin;
        }

        public bool ModeMin
        {
            get { return m_bModeMin; }
            set { m_bModeMin = value;}
        }

        public override UnsafeBitmap Execute(UnsafeBitmap _bitmap)
        {
            int nWidth = _bitmap.Width;
            int nHeight = _bitmap.Height;

            int rMin = int.MaxValue;
            int gMin = int.MaxValue;
            int bMin = int.MaxValue;

            int rMax = int.MinValue;
            int gMax = int.MinValue;
            int bMax = int.MinValue;
            for (int y = 0; y < nHeight; y++)
            {
                for (int x = 0; x < nWidth; x++)
                {
                    Color color = _bitmap.GetPixel(x, y);

                    if (color.R < rMin) rMin = color.R;
                    if (color.G < gMin) gMin = color.G;
                    if (color.B < bMin) bMin = color.B;

                    if (color.R > rMax) rMax = color.R;
                    if (color.G > gMax) gMax = color.G;
                    if (color.B > bMax) bMax = color.B;
                }
            }

            if ((m_bModeMin && rMin == 0 && gMin == 0 && bMin == 0)
                || !m_bModeMin && rMax == 255 && gMax == 255 && bMax == 255)
            {
               return _bitmap;
            }

            for (int y = 0; y < nHeight; y++)
            {
                for (int x = 0; x < nWidth; x++)
                {
                    Color color = _bitmap.GetPixel(x, y);
                    if (m_bModeMin)
                    {
                        _bitmap.SetPixel(x, y, Color.FromArgb(color.R - rMin, color.G - gMin, color.B - bMin));
                    }
                    else
                    {
                        _bitmap.SetPixel(x, y, Color.FromArgb(color.R + (255 - rMax), color.G + (255 - gMax), color.B + (255 - bMax)));
                    }
                }
            }
            return _bitmap;
        }

        public override object Clone()
        {
            return new ShiftOffset(this);
        }
    }
}
